#include "transparenttimer.h"

#include <QPainter>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QLineEdit>
#include <QLabel>
#include <QStyleOption>
#include <QGraphicsDropShadowEffect>
#include <QFile>
#include <QDir>

#define iconSize 30
const QString TransparentTimer::c_iconPath =  QString(QDir::currentPath() + "/qIcon/");

TransparentTimer::TransparentTimer(QWidget *parent)
        : QWidget(parent)
{
    // 设置窗口属性
    setWindowFlags(Qt::FramelessWindowHint);
    setAttribute(Qt::WA_TranslucentBackground);
    setMinimumSize(150, 100);
    setMouseTracking(true); // 开启鼠标追踪

    // 创建定时器
    timer = new QTimer(this);
    connect(timer, &QTimer::timeout, this, &TransparentTimer::updateTimer);

    // 创建UI
    mainWidget = new QWidget(this);
    mainWidget->setObjectName("mainWidget"); // 设置对象名以便在CSS中引用

    topButton = new QPushButton();
    topButton->setIcon(QIcon(c_iconPath + "topdown.png"));
    topButton->setFixedSize(iconSize, iconSize);
    topButton->setChecked(false);
    topButton->setObjectName("topButton"); // 设置对象名以便在CSS中引用
    connect(topButton, &QPushButton::clicked, this, &TransparentTimer::toggleTopmost);

    // 添加关闭按钮
    closeButton = new QPushButton( this);
    closeButton->setIcon(QIcon(c_iconPath + "close.png"));
    closeButton->setFixedSize(iconSize, iconSize);
    closeButton->setObjectName("closeButton");
    connect(closeButton, &QPushButton::clicked, this, &QWidget::close);

    // 添加最小化按钮
    minimizeButton = new QPushButton(this);
    minimizeButton->setIcon(QIcon(c_iconPath + "minim.png"));
    minimizeButton->setFixedSize(iconSize, iconSize);
    minimizeButton->setObjectName("minimizeButton");
    connect(minimizeButton, &QPushButton::clicked, this, &QWidget::showMinimized);

    QHBoxLayout *topLayout = new QHBoxLayout();
    topLayout->addStretch(1);
    topLayout->addWidget(topButton);
    topLayout->addWidget(minimizeButton);
    topLayout->addWidget(closeButton);

    // 时间显示
    timeLabel = new QLabel("00:00:00.00");
    timeLabel->setObjectName("timeLabel");

    startButton = new QPushButton();
    startButton->setObjectName("startButton"); // 设置对象名以便在CSS中引用
    startButton->setIcon(QIcon(c_iconPath + "start.png"));
    startButton->setFixedSize(iconSize, iconSize);
    connect(startButton, &QPushButton::clicked, this, &TransparentTimer::toggleTimer);

    resetButton = new QPushButton();
    resetButton->setObjectName("resetButton"); // 设置对象名以便在CSS中引用
    resetButton->setIcon(QIcon(c_iconPath + "reset.png"));
    resetButton->setFixedSize(iconSize, iconSize);
    connect(resetButton, &QPushButton::clicked, this, &TransparentTimer::resetTimer);

    // 显示区域
    QHBoxLayout *playLayout = new QHBoxLayout();
    playLayout->addWidget(timeLabel, 1);
    playLayout->addWidget(startButton);
    playLayout->addWidget(resetButton);

    rateLabel = new QLabel("分均: 0");
    rateLabel->setObjectName("rateLabel");

    problemInput = new QLineEdit();
    problemInput->setPlaceholderText("得分");
    problemInput->setValidator(new QIntValidator(0, 99999, this));
    problemInput->setMaximumWidth(65);
    connect(problemInput, &QLineEdit::textChanged, this, &TransparentTimer::calculateRate);

    // 输入区域
    QHBoxLayout *inputLayout = new QHBoxLayout();
    inputLayout->addWidget(rateLabel, 1);
    inputLayout->addWidget(problemInput);

    QVBoxLayout *mainLayout = new QVBoxLayout(mainWidget);
    mainLayout->addLayout(topLayout);
    mainLayout->addLayout(playLayout);
    mainLayout->addLayout(inputLayout);

    // 设置主窗口布局
    QVBoxLayout *windowLayout = new QVBoxLayout(this);
    windowLayout->setContentsMargins(0, 0, 0, 0);
    windowLayout->addWidget(mainWidget);

    // 加载CSS文件
    QFile file("timer.css");
    if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        QTextStream in(&file);
        QString styleSheet = in.readAll();
        setStyleSheet(styleSheet);
        file.close();
    }
}

void TransparentTimer::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event);
    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);

    // 绘制半透明背景
    painter.setBrush(QColor(10, 10, 20, 30));
    painter.setPen(Qt::NoPen);
    painter.drawRoundedRect(rect(), 12, 12);
}

void TransparentTimer::mousePressEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton) {
        if (resizeRegion != 0) {
            isResizing = true;
            dragPosition = event->globalPosition().toPoint();
        } else {
            // 拖动窗口
            dragPosition = event->globalPosition().toPoint() - frameGeometry().topLeft();
            event->accept();
        }
    }
}

void TransparentTimer::mouseMoveEvent(QMouseEvent *event)
{
    QPoint globalPoint = event->globalPosition().toPoint();

    if (!isResizing) {
        // 更新光标形状
        updateCursorShape(event->pos());

        // 拖动窗口
        if (event->buttons() & Qt::LeftButton) {
            move(globalPoint - dragPosition);
            event->accept();
        }
    }
}

void TransparentTimer::mouseReleaseEvent(QMouseEvent *event)
{
    Q_UNUSED(event);
    isResizing = false;
}

void TransparentTimer::updateCursorShape(const QPoint &point)
{
    // 更新鼠标区域
    updateMouseRegion();
}

void TransparentTimer::updateMouseRegion()
{
    resizeRegion = 0;

    // 获取鼠标相对于窗口的位置
    QPoint pos = mapFromGlobal(QCursor::pos());

    // 检查是否在边缘区域
    if (pos.y() <= BORDER_WIDTH) {
        if (pos.x() <= BORDER_WIDTH)
            resizeRegion = 5; // 左上角
        else if (pos.x() >= width() - BORDER_WIDTH)
            resizeRegion = 6; // 右上角
        else
            resizeRegion = 1; // 上边缘
    }
    else if (pos.y() >= height() - BORDER_WIDTH) {
        if (pos.x() <= BORDER_WIDTH)
            resizeRegion = 7; // 左下角
        else if (pos.x() >= width() - BORDER_WIDTH)
            resizeRegion = 8; // 右下角
        else
            resizeRegion = 2; // 下边缘
    }
    else if (pos.x() <= BORDER_WIDTH) {
        resizeRegion = 3; // 左边缘
    }
    else if (pos.x() >= width() - BORDER_WIDTH) {
        resizeRegion = 4; // 右边缘
    }
}

void TransparentTimer::updateTimer()
{
    //totalSeconds = elapsedTimer.elapsed() / 1000.0;
    // totalSeconds = elapsedSeconds / 1000.0;
    elapsedSeconds = totalSeconds + elapsedTimer.elapsed() / 1000.0;

    int hours = static_cast<int>(elapsedSeconds) / 3600;
    int minutes = (static_cast<int>(elapsedSeconds) % 3600) / 60;
    int seconds = static_cast<int>(elapsedSeconds) % 60;
    int milliseconds = static_cast<int>(elapsedSeconds * 100) % 100;

    QLabel *timeLabel = findChild<QLabel*>("timeLabel");
    if (timeLabel) {
        timeLabel->setText(QString("%1:%2:%3.%4")
                                   .arg(hours, 2, 10, QLatin1Char('0'))
                                   .arg(minutes, 2, 10, QLatin1Char('0'))
                                   .arg(seconds, 2, 10, QLatin1Char('0'))
                                   .arg(milliseconds, 2, 10, QLatin1Char('0')));
    }

    calculateRate();
}

void TransparentTimer::toggleTimer()
{
//    if (isRunning) {
//        timer->stop();
//        isRunning = false;
//        startButton->setIcon(QIcon(c_iconPath + "start.png"));
//    } else {
//        elapsedTimer.start();
//        timer->start(10); // 更新间隔10ms
//        isRunning = true;
//        startButton->setIcon(QIcon(c_iconPath + "stop.png"));
//    }
    if (isRunning) {
        // 暂停计时器
        timer->stop();
        isRunning = false;
        totalSeconds += elapsedTimer.elapsed() / 1000.0; // 累加已过时间
        startButton->setIcon(QIcon(c_iconPath + "start.png"));
    } else {
        // 继续计时
        elapsedTimer.restart(); // 重新开始计时器，但总时间不变
        timer->start(10); // 更新间隔10ms
        isRunning = true;
        startButton->setIcon(QIcon(c_iconPath + "stop.png"));
    }
}

void TransparentTimer::resetTimer()
{
    timer->stop();
    isRunning = false;
    totalSeconds = 0;
    elapsedTimer.invalidate(); // 使计时器无效

    QLabel *timeLabel = findChild<QLabel*>("timeLabel");
    if (timeLabel) {
        timeLabel->setText("00:00:00.00");
    }

    QLineEdit *problemInput = findChild<QLineEdit*>();
    if (problemInput) {
        problemInput->clear();
    }

    calculateRate();
}

void TransparentTimer::toggleTopmost()
{
    isTopmost = !isTopmost;
    setWindowFlag(Qt::WindowStaysOnTopHint, isTopmost);
    show();

    QPushButton *topButton = qobject_cast<QPushButton*>(sender());
    if (topButton) {
        topButton->setIcon(QIcon(c_iconPath + (isTopmost ? "topup.png" : "topdown.png")));
    }
}

void TransparentTimer::calculateRate()
{
    QLineEdit *problemInput = findChild<QLineEdit*>();
    QLabel *rateLabel = findChild<QLabel*>("rateLabel");


    if (problemInput && rateLabel) {
        bool ok;
        problemCount = problemInput->text().toInt(&ok);

        if (ok && problemCount > 0 && elapsedSeconds > 0) {
            rate = problemCount / (elapsedSeconds / 60.0);
            if (rate > 100000) {
                rateLabel->setText(QString("分均: %1").arg(100000 ));
            } else {
                rateLabel->setText(QString("分均: %1").arg(rate));
            }
        } else {
            rateLabel->setText("分均: 0");
        }
    }
}